<?php

/**
 * 标签过滤
 * @return true|false
 */
function smsTag($content, $data = array())
{
    foreach ($data as $k => $v) {
        $content = str_replace('{' . $k . '}', $v, $content);
    }
    return $content;
}

/**
 * 发送短信方法
 * @param string	$mobile		手机号码;
 * @param string    $content    短信内容;
 * @param int	    $memberID   会员ID;
 * @param string    $code   	验证码;
 * @return true|false
 */
function sendSms($mobile, $content, $memberID = 0, $code) {
    if (empty($mobile) || empty($content)){
        return false;
    }
    if (getConfig('sms') != 1){
        return false;
    }
    $smsSign = getConfig('sms_sign');
    $content .= $smsSign;
	$result = submitSms($mobile, $content);
	$data = array(
	    "member_id" => $memberID,
	    "mobile" => $mobile,
	    "message" => $content,
	    "sms_result" => $result,
	    "sms_type" => ! empty($code) ? 1 : 0,
	    "sms_code" => $code,
	    "create_time" => time(),
	    "update_time" => time(),
	);
	$rs = M('SmsLog')->add($data);
	return $rs;

}

function submitSms($mobile, $content)
{
    $smsHost = getConfig('sms_host');
    $smsUer = getConfig('sms_user');
    $smsPwd = getConfig('sms_password');
    $smsParams = getConfig('sms_params');
    $smsParams = json_decode($smsParams, true);
    $smsExtend = getConfig('sms_extend');
    $smsExtend = json_decode($smsExtend, true);

    $params = array(
        $smsExtend['sms_user_field'] => $smsUer,
        $smsExtend['sms_password_field'] => $smsPwd,
        $smsExtend['sms_mobie_field'] => $mobile,
        $smsExtend['sms_content_field'] => $content,
    );
    
    $params = array_merge($params, $smsParams);
    $result = curlHttp($smsHost, $params, 'POST');
    return $result;
}

function smsPost($mobile, $content)
{
    $host = getConfig('sms_host');
    $data = "sname=" . getConfig('sms_user') . "&spwd=" . getConfig('sms_password') . "&scorpid=&sprdid=1012818&sdst={$mobile}&smsg=" . rawurlencode($content);
    $hostInfo = parse_url($host);
    $header  = "POST " . $hostInfo['path'] . " HTTP/1.0\r\n";
    $header .= "Host:" . $hostInfo['host'] . "\r\n";
    $header .= "Content-Type:application/x-www-form-urlencoded\r\n";
    $header .= "Content-Length:" . strlen($data) . "\r\n";
    $header .= "Connection:close\r\n\r\n";
    // $header .= "Connection:Keep-Alive\r\n\r\n";
    $header .= $data;
    
    $fd = fsockopen($hostInfo['host'], 80);
    fwrite($fd, $header);
    $gets = "";
    while (! feof($fd)) {
        $gets .= fread($fd, 128);
    }
    fclose($fd);
    if ($gets != '') {
        $start = strpos($gets, '<?xml');
        if ($start > 0) {
            $gets = substr($gets, $start);
        }
    }
    return $gets;
}

?>